package edu.cs3240.nfa;

import java.util.ArrayList;

public class Part {
	private State start;
	private Transition defaultTransition;
	
	public Part()
	{
		start = new State();
		defaultTransition = new Transition(start, null);
		start.addTransition(defaultTransition);
	}
	
	public void concat(Part part)
	{
		defaultTransition = null;
		for(Transition t : getEnds())
		{
			t.pointTo(part.start);			
		}
	}
	/**
	 * Connect the end of this part to a new state that has the given dangling transition
	 * @param state
	 * @param dangling
	 */
	public void concat(State state)
	{
		defaultTransition = null;
		for(Transition t : getEnds())
		{
			t.pointTo(state);			
		}
	}
	public void union(Part part)
	{
		if(defaultTransition != null)
			start.getTransitions().remove(defaultTransition);
		
		start.addTransition(new Transition(start, part.start));
	}
	
	/**
	 * The start of this part
	 * @return
	 */
	public State getStart()
	{
		return start;
	}
	
	/**
	 * Get all dangling transitions in this part
	 * @return
	 */
	private ArrayList<Transition> getEnds()
	{
		return getEnds(start);		
	}
	private ArrayList<Transition> getEnds(State root)
	{
		ArrayList<Transition> dangling = new ArrayList<Transition>();
		for(Transition t : root.getTransitions())
		{
			if(!t.isConnected()) 
			{
				dangling.add(t);
			}
			else
			{
				dangling.addAll(getEnds(t.getTo()));
			}
		}
		return dangling;
	}

	
	@Override
	public String toString()	
	{
		return start.toString();		
	}
}
